const mongoose = require('mongoose')
const validator = require('validator')
const bcrypt = require('bcryptjs')

const userSchema = new mongoose.Schema(
  {
    username: {
      type: String,
      required: true,
      unique: true,
      trim: true,
      minlength: 3,
    },
    name: String,
    email: {
      type: String,
      required: true,
      unique: true,
      validate: [validator.isEmail, '邮箱格式不正确'],
    },
    password: {
      type: String,
      required: true,
      minlength: [6, '密码长度不能少于6位'],
      select: false,
    },
    avatar: {
      type: String,
      validate: [validator.isURL, '头像url格式不正确'],
    },
    role: {
      type: String,
      enum: ['admin', 'user', 'visitor'],
      default: 'visitor',
    },
    github: String,
    gitee: String,
    juejin: String,
    description: String,
  },
  { timestamps: true },
)

// 密码加密中间件
userSchema.pre('save', async function (next) {
  // 如果修改的不是密码，就不用管
  if (!this.isModified('password')) return next()

  // 进行加密
  this.password = await bcrypt.hash(this.password, 12)
})

// 验证密码
userSchema.methods.correctPassword = function (candidatePassword, userPassword) {
  return bcrypt.compare(candidatePassword, userPassword)
}

const User = mongoose.model('User', userSchema)

module.exports = User
